import { Component, OnInit, OnDestroy } from '@angular/core'
import { FormBuilder, Validators, FormGroup } from '@angular/forms'
import { Subject } from 'rxjs'
import { debounceTime, takeUntil } from 'rxjs/operators'
import { NzMessageService } from 'ng-zorro-antd'
import { SettingsService } from '@delon/theme'

import { StoreNewBaseClass } from '../baseClass'
import { StoreDataService } from '../../store-data.service'
import {
  makeAllControlDirty,
  getAAMSAcquirer,
  getAAMSGroup,
  getAAMSMerchant,
  acquirerEditPermission,
  agentEditPermission,
  merchantEditPermission,
} from 'app/utils/helpers'
import { IAamsItem } from '@shared/components/aams-select/aams-select.interface'
import { User } from '@shared/interfaces/user'
import { I18NService } from '@core'

@Component({
  selector: 'app-store-new-system',
  templateUrl: './system.component.html',
})
export class StoreNewSystemComponent extends StoreNewBaseClass implements OnInit, OnDestroy {
  constructor(
    public msg: NzMessageService,
    public fb: FormBuilder,
    public storeService: StoreDataService,
    public settings: SettingsService,
    private i18n: I18NService,
  ) {
    super(fb, storeService)
  }

  chosenAcquirer: IAamsItem = {}
  chosenGroup: IAamsItem = {}
  chosenMerchant: IAamsItem = {}
  groupRestorer$ = new Subject()
  merchantRestorer$ = new Subject()
  destroy$ = new Subject()

  ngOnInit() {
    this.initValidateForm()
    this.subscribeObservables()
  }

  ngOnDestroy(): void {
    this.destroy$.next()
    this.destroy$.complete()
  }

  initValidateForm(): void {
    const { common } = this.storeService.value.store
    const authUser = this.settings.user as User

    let fg: FormGroup
    if (common.insCode && common.intMerCode) {
      this.chosenAcquirer = {
        num: common.insCode,
        code: common.insCode,
        name: common.insName,
        nameEN: common.insNameEN,
      }

      if (common.agentCode) {
        this.chosenGroup = {
          num: common.agentCode,
          code: common.agentCode,
          name: common.agentName,
          nameEN: common.agentNameEN,
        }
      }
      this.chosenMerchant = {
        num: common.merNum,
        code: common.intMerCode,
        name: common.merName,
        nameEN: common.merNameEN,
      }
    } else {
      this.chosenAcquirer = getAAMSAcquirer(authUser)
      this.chosenGroup = getAAMSGroup(authUser)
      this.chosenMerchant = getAAMSMerchant(authUser)
    }
    // 填充信息
    fg = this.fb.group({
      acquirer: [
        {
          value: this.chosenAcquirer.code ? this.chosenAcquirer : null,
          disabled: acquirerEditPermission(authUser),
        },
        [Validators.required],
      ],
      acquirerName: [
        {
          value: this.chosenAcquirer.name,
          disabled: true,
        },
      ],
      acquirerNameEN: [
        {
          value: this.chosenAcquirer.nameEN,
          disabled: true,
        },
      ],
      group: [
        {
          value: this.chosenGroup.code ? this.chosenGroup : null,
          disabled: agentEditPermission(authUser),
        },
      ],
      groupName: [
        {
          value: this.chosenGroup.name,
          disabled: true,
        },
      ],
      groupNameEN: [
        {
          value: this.chosenGroup.nameEN,
          disabled: true,
        },
      ],
      merchant: [
        {
          value: this.chosenMerchant.code ? this.chosenMerchant : null,
          disabled: merchantEditPermission(authUser),
        },
        [Validators.required],
      ],
      merchantName: [
        {
          value: this.chosenMerchant.name,
          disabled: true,
        },
      ],
      merchantNameEN: [
        {
          value: this.chosenMerchant.nameEN,
          disabled: true,
        },
      ],
    })
    this.validateForm = fg
  }

  checkValid(): boolean {
    if (this.validateForm.valid || this.validateForm.status === 'DISABLED') {
      this.pushDataToStore()
      return true
    }

    makeAllControlDirty(this.validateForm)
    this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    return false
  }

  pushDataToStore(): void {
    this.store.store.common.insCode = this.chosenAcquirer.code
    this.store.store.common.insName = this.chosenAcquirer.name
    this.store.store.common.insNameEN = this.chosenAcquirer.nameEN
    this.store.store.common.agentCode = this.chosenGroup.code
    this.store.store.common.agentName = this.chosenGroup.name
    this.store.store.common.agentNameEN = this.chosenGroup.nameEN
    this.store.store.common.merNum = this.chosenMerchant.num
    this.store.store.common.intMerCode = this.chosenMerchant.code
    this.store.store.common.merName = this.chosenMerchant.name
    this.store.store.common.merNameEN = this.chosenMerchant.nameEN
    this.storeService.setValue(this.store)
  }

  /** 选中选项 */
  handleChosenAcquirer(value: IAamsItem): void {
    if (!value) {
      value = {}
    }

    this.chosenAcquirer = value
    this.validateForm.get('acquirerName').setValue(value.name)
    this.validateForm.get('acquirerNameEN').setValue(value.nameEN)

    this.groupRestorer$.next()
    this.merchantRestorer$.next()
  }

  handleChosenGroup(value: IAamsItem | null): void {
    if (!value) {
      value = {}
    }

    this.chosenGroup = value
    this.validateForm.get('groupName').setValue(value.name)
    this.validateForm.get('groupNameEN').setValue(value.nameEN)

    this.merchantRestorer$.next()
  }

  handleChosenMerchant(value: IAamsItem | null): void {
    if (!value) {
      value = {}
    }

    this.chosenMerchant = value
    this.validateForm.get('merchantName').setValue(value.name)
    this.validateForm.get('merchantNameEN').setValue(value.nameEN)
    this.store.store.common.intMerCode = this.chosenMerchant.code
  }

  private subscribeObservables() {
    this.groupRestorer$
      .asObservable()
      .pipe(
        takeUntil(this.destroy$),
        debounceTime(300),
      )
      .subscribe(() => {
        this.resetGroup()
      })

    this.merchantRestorer$
      .asObservable()
      .pipe(
        takeUntil(this.destroy$),
        debounceTime(300),
      )
      .subscribe(() => {
        this.resetMerchant()
      })
  }

  private resetGroup(): void {
    const selectedGroup = this.validateForm.get('group').value
    if (selectedGroup) {
      this.validateForm.get('group').setValue(null)
      this.validateForm.get('groupName').setValue('')
      this.validateForm.get('groupNameEN').setValue('')
    }
  }

  private resetMerchant(): void {
    const selectedMerchant = this.validateForm.get('merchant').value
    if (selectedMerchant) {
      this.validateForm.get('merchant').setValue(null)
      this.validateForm.get('merchantName').setValue('')
      this.validateForm.get('merchantNameEN').setValue('')
    }
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
